package com.newshub.admin.service.impl;

import com.newshub.admin.entity.RssFeed;
import com.newshub.admin.mapper.RssFeedMapper;
import com.newshub.admin.service.FetchTaskService;
import com.newshub.admin.service.RssFetchLogService;
import com.newshub.business.dto.PageResult;
import com.newshub.monitor.dto.TaskWithSuccessRate;
import com.newshub.logging.annotation.BusinessLog;
import com.newshub.logging.annotation.LogLevel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FetchTaskServiceImpl implements FetchTaskService {

    @Autowired
    private RssFeedMapper rssFeedMapper;
    
    @Autowired
    private RssFetchLogService rssFetchLogService;

    @Override
    @BusinessLog(module = "抓取任务管理", description = "分页查询抓取任务列表", level = LogLevel.INFO)
    public List<Map<String, Object>> listTasks(Integer pageNum, Integer pageSize, Integer status) {
        int safePageNum = pageNum == null || pageNum < 1 ? 1 : pageNum;
        int safePageSize = pageSize == null || pageSize < 1 ? 10 : pageSize;
        int offset = (safePageNum - 1) * safePageSize;

        List<RssFeed> feeds = rssFeedMapper.selectByPage(offset, safePageSize, null, status, null, null);
        List<Map<String, Object>> tasks = new ArrayList<>();
        for (RssFeed feed : feeds) {
            Map<String, Object> t = new HashMap<>();
            t.put("taskType", "RSS");
            t.put("feedId", feed.getId());
            t.put("name", feed.getName());
            t.put("status", feed.getStatus());
            t.put("fetchTime", feed.getFetchTime());
            t.put("lastFetchDate", feed.getLastFetchDate());
            t.put("lastFetchAt", feed.getLastFetchAt());
            t.put("errorCount", feed.getErrorCount());
            t.put("fetchCount", feed.getFetchCount());
            tasks.add(t);
        }
        return tasks;
    }

    @Override
    @BusinessLog(module = "抓取任务管理", description = "统计抓取任务数量", level = LogLevel.INFO)
    public Long countTasks(Integer status) {
        return rssFeedMapper.countByPage(null, status, null, null);
    }
    
    @Override
    @BusinessLog(module = "抓取任务管理", description = "分页查询任务列表（含成功率）", level = LogLevel.INFO)
    public PageResult<TaskWithSuccessRate> getTasksWithSuccessRate(Integer status, Integer days, Integer pageNum, Integer pageSize) {
        // 验证天数参数
        if (days != 7 && days != 14 && days != 30) {
            days = 7; // 默认7天
        }
        
        int safePageNum = pageNum == null || pageNum < 1 ? 1 : pageNum;
        int safePageSize = pageSize == null || pageSize < 1 ? 10 : pageSize;
        int offset = (safePageNum - 1) * safePageSize;

        // 1. 获取分页任务列表
        List<RssFeed> feeds = rssFeedMapper.selectByPage(offset, safePageSize, null, status, null, null);
        Long total = rssFeedMapper.countByPage(null, status, null, null);
        
        // 2. 提取RSS源ID列表
        List<Long> feedIds = feeds.stream()
                .map(feed -> feed.getId().longValue())
                .toList();
        
        // 3. 批量查询成功率统计
        Map<Long, Map<String, Object>> successRates = rssFetchLogService.batchGetSuccessRates(feedIds, days);
        
        // 4. 组装结果
        List<TaskWithSuccessRate> resultList = new ArrayList<>();
        for (RssFeed feed : feeds) {
            Long feedId = feed.getId().longValue();
            Map<String, Object> rateData = successRates.get(feedId);
            
            TaskWithSuccessRate task = TaskWithSuccessRate.builder()
                    .taskType("RSS")
                    .feedId(feedId)
                    .name(feed.getName())
                    .status(feed.getStatus())
                    .fetchTime(feed.getFetchTime())
                    .lastFetchDate(feed.getLastFetchDate() != null ? feed.getLastFetchDate().toString() : null)
                    .lastFetchAt(feed.getLastFetchAt() != null ? feed.getLastFetchAt().toString() : null)
                    .errorCount(feed.getErrorCount())
                    .fetchCount(feed.getFetchCount())
                    .successRate(rateData != null ? (Double) rateData.get("successRate") : 0.0)
                    .effectiveSuccessRate(rateData != null ? (Double) rateData.get("effectiveSuccessRate") : 0.0)
                    .days(days)
                    .build();
            
            resultList.add(task);
        }
        
        return PageResult.of(safePageNum, safePageSize, total, resultList);
    }
}




